package com.education.util;

import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zhanjun on 2015/1/19.
 */
public class HtmlUtil {

	/**
	 *
	 * @param requestUrl
	 * @return
	 */
	public static String getContent(String requestUrl) {
		InputStream in = null;
		try {
			in = getHttpURLConnectionInputStream(requestUrl, null, null);
			byte[] contents = new byte[1024];
			StringBuffer sb = new StringBuffer();
			int len;
			while ((len = in.read(contents)) != -1) {
				sb.append(new String(contents));
			}

			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 所有html全部去掉
	 */
	private static String removeHtmlTag(String html) {
		if (DataUtil.isEmpty(html)) {
			return "";
		}
		String result = html.replaceAll("<[/]?[^>]+>", "").replaceAll("&nbsp;", "");
		return result;
	}

	/**
	 * 根据HttpURLConnection获取输入流
	 * @param requestUrl
	 * @param param
	 * @param inetSocketAddress
	 * @return
	 */
	public static InputStream getHttpURLConnectionInputStream(String requestUrl, Map<String, String> param, InetSocketAddress inetSocketAddress) throws IOException {
		URL url;
		HttpURLConnection conn;
		try {
			url = new URL(requestUrl);
			if (inetSocketAddress != null) {
				Proxy proxy = new Proxy(Proxy.Type.HTTP, inetSocketAddress);
				conn = (HttpURLConnection) url.openConnection(proxy);
			} else {
				conn = (HttpURLConnection) url.openConnection();
			}

			conn.setConnectTimeout(1000); //请求超时
			conn.setReadTimeout(1000); //读取超时
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "applaction/x-www-form-urlencoded");

			if (MapUtils.isNotEmpty(param)) {
				StringBuilder sb = new StringBuilder();
				Iterator<String> it = param.keySet().iterator();
				while (it.hasNext()) {
					String key = it.next();
					String value = param.get(key);
					sb.append(key).append("=").append(value).append("&");
				}

				conn.setRequestMethod("POST"); //请求方式
				String p = sb.toString().substring(0, sb.length() - 1);
				OutputStream os = conn.getOutputStream();
				os.write(p.getBytes("UTF-8"));
				os.close();
			} else {
				conn.setRequestMethod("GET"); //请求方式
			}

			if (conn == null) {
				throw new IOException("conn is null");
			}

			return conn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 使用HttpURLConnection请求Internet
	 *
	 * @param requestUrl  请求的URL
	 * @param param       请求的参数
	 * @param proxy  代理参数
	 * @return 返回一个inputstream流
	 */
	public static InputStream getHttpClientInputStream(String requestUrl, Map<String, String> param, HttpHost proxy) throws Exception {
		HttpClient client = new DefaultHttpClient();
		if (proxy != null) {   //当请求的网络为需要使用代理时
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		}

		HttpResponse response;
		if(MapUtils.isEmpty(param)) {
			HttpGet hg = new HttpGet(requestUrl);
			hg.setHeader("Charset", "UTF-8");
			hg.setHeader("Content-Type", "application/x-www-form-urlencoded");
			response = client.execute(hg);
		} else {
			HttpPost hp = new HttpPost(requestUrl);
			hp.setHeader("Charset", "UTF-8");
			hp.setHeader("Content-Type", "application/x-www-form-urlencoded");
			List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
			Iterator<String> it = param.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				list.add(new BasicNameValuePair(key, param.get(key)));
			}
			hp.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
			response = client.execute(hp);
		}
		return response.getEntity().getContent();
	}

}
